package cn.thoughtworks.school.repositories;


import cn.thoughtworks.school.entities.UserQuizGroup;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface UserQuizGroupRepository extends JpaRepository<UserQuizGroup, Long> {
  List<UserQuizGroup> findByUserId(Long userId);

  UserQuizGroup findByUserIdAndQuizGroupId(Long userId, Long quizGroupId);

  Page<UserQuizGroup> findByQuizGroupId(Long quizGroupId, Pageable pageable);

  @Query(value = "select userQuizGroup.* from userQuizGroup JOIN " +
    " (select  id from quizGroup  where organizationId = :organizationId) quizG " +
    " where userQuizGroup.userId=:userId  and userQuizGroup.quizGroupId= quizG.id", nativeQuery = true)
  List<UserQuizGroup> findByUserIdAndOrganizationId(@Param("userId") Long userId,
                                                    @Param("organizationId") Long organizationId);

  @Modifying
  @Transactional
  @Query(value = "DELETE  FROM  UserQuizGroup userGroup WHERE  userGroup.userId=:quizGroupId")
  void deleteByQuizGroupId(@Param("quizGroupId") Long quizGroupId);

}
